package Controls
{
	import Layout.GameLayout;
	
	import Objects.GameSprite;
	
	import Plugin.TogglePlugin;
	
	import Tools.DisplayTool;
	
	import flash.display.Sprite;

	public class Tree extends GameSprite
	{
		public var renderList:Array=[];
		public var renderClass:Class;
		public var toggle:TogglePlugin;
		public var callBackHandler:Function;
		public function Tree()
		{
			super();
			
			intelligent=true;
		}
		override protected function $update():void
		{
			layout();
		}
		private function layout():void
		{
			var list:Array;
			list= renderList.filter(function (treeItem:TreeItem, index:int, arr:Array):Boolean{
				return treeItem.obj.visible;
			});
			list.forEach(function (treeItem:TreeItem, index:int, arr:Array):void{
				treeItem.layout(index);
			});
		}
		public function setup(dataList:Array):void
		{
			DisplayTool.removeObjects(renderList);
			
			renderList=new Array();
			
			createNotes(dataList);
			
			if(toggle)
			{
				toggle.remove();
			}
			
			toggle=gs.addToggle(renderList,selectHandler);
		}
		private function selectHandler(index:int):void
		{
			var itemRender:TreeItem=renderList[index];
			if(callBackHandler)
			{
				callBackHandler(itemRender.data);
			}
		}
		private function createNotes(dataList:Array,parentNote:TreeItem=null):void
		{
			var index:int=0;
			while(index<dataList.length)
			{
				var data:Object=dataList[index];
				var itemRender:TreeItem=new renderClass();
				addChild(itemRender);
				itemRender.parentNote=parentNote;
				itemRender.elderNotes=itemRender.getElderNotes();
				itemRender.data=data;
				renderList.push(itemRender);
				if(data["value"] is Array)
				{
					createNotes(data["value"],itemRender);
				}
				index++;
			}
		}
	}
}